<template>
  <view class="out">
    <checkbox-group @change="itemChange">
      <view class="item" v-for="good in goods" :key="good.id">
        <checkbox :value="good.id" :checked="good.checked"></checkbox>
        <text class="title" :key="good.id">{{ good.name }}</text>
        <text class="del" @click="remove(index)">删除</text>
      </view>
    </checkbox-group>

    <view class="card">
      <view class="text">选中{{ totalNumber }}个,总价{{ totalPrice }}元</view>
    </view>

    {{ selectGroups }}
    <view>---</view>
    {{ goods }}
  </view>
</template>

<script setup>
import { computed, ref } from "vue";

const goods = ref([
  { id: "11", name: "小米", price: 2342, checked: false },
  { id: "22", name: "华为", price: 4564, checked: false },
  { id: "33", name: "oppo", price: 8639, checked: false },
  { id: "44", name: "苹果", price: 3224, checked: false },
]);

const selectGroups = ref([]);
const totalNumber = computed(() => selectGroups.value.length);
const totalPrice = computed(() =>
  goods.value
    .filter((item) => item.checked)
    .reduce((pre, cur) => pre + cur.price, 0)
);

function remove(index) {
  goods.value.splice(index, 1);
}

function itemChange(e) {
  selectGroups.value = e.detail.value;
  goods.value.forEach((item) => {
    item.checked = e.detail.value.includes(item.id);
  });
}
</script>

<style lang="scss">
.out {
  padding: 10px;

  .item {
    padding: 10px 0;

    .del {
      color: #c00;
      margin-left: 30px;
    }
  }
}
</style>
